<template>
  <div py-16rpx>
    <!-- 参考h5版本的京东 -->

    <nut-swipe-group lock>
      <div p-16rpx bg-white v-for="(item, index) in goodsList" :key="index">
        <nut-swipe :name="item.id">
          <oneRow :res="item" />
          <template #right>
            <nut-button @click="handleClickGoods(item)" :custom-style="{ height: '100%' }" h-full type="danger"
              shape="square">删除</nut-button>
          </template>
        </nut-swipe>
      </div>
    </nut-swipe-group>
    <div class="mp-iphonex-bottom" bottom-0 position-fixed flex flex-a-c h-100rpx bg-white w-full>

      <nut-button @click="warning = true" type="default" block link px-16rpx justify-end flex flex-a-c h-full flex-j-sb>
        全部清除
      </nut-button>

    </div>

    <nut-dialog title="提示" content="是否清除全部浏览记录？" v-model:visible="warning" @ok="confirmDelete" />

  </div>
</template>

<script setup lang="ts">
import { deleteTracks, getTracks } from '@/api/member';
import oneRow from '@/components/goods-list/1row.vue';
import type { GoodsListType } from '@/components/goods-list/types';
import type { Search } from '@/constants/types';
import { onPullDownRefresh, onReachBottom, onShow } from '@dcloudio/uni-app';
const goodsList = ref<Array<GoodsListType>>([])
const goodsData = ref<any>('')
const warning = ref<boolean>(false)
const searchForm = ref<Search>({
  pageNumber: 1,
  pageSize: 18,
  order: 'desc',
  sort: 'updateTime',
})

async function init() {
  goodsList.value = []
  searchForm.value.pageNumber = 1
  fetchTracks()
}

async function confirmDelete() {

  // 先给商品内容去重
  const ids = goodsList.value.map(item => item.goodsId)
  const res = await deleteTracks(ids);
  if (res.data.success) {
    uni.showToast({
      title: "删除成功!",
      icon: "none"
    })
    init()
  }
}

async function handleClickGoods(item: GoodsListType) {
  const ids = item.goodsId
  const res = await deleteTracks(ids);
  if (res.data.success) {
    uni.showToast({
      title: "删除成功!",
      icon: "none"
    })
    init()
  }
}


async function fetchTracks() {
  uni.stopPullDownRefresh();
  const res = await getTracks(searchForm.value)
  if (res.data.success) {
    goodsList.value.push(...res.data.result.records)
    goodsData.value = res.data.result
  }
}


onPullDownRefresh(() => {
  init()
})

onReachBottom(() => {
  if (goodsData.value?.total > searchForm.value.pageNumber * searchForm.value.pageSize) {
    searchForm.value.pageNumber++;
    fetchTracks()
  }
})

onShow(() => {
  init()
})
</script>

<style scoped lang="scss">
:v-deep(.nut-button) {
  height: 100%;
}

::v-deep .nut-swipe__right .nut-button {
  height: 100%;
  margin-left: 16rpx;
}
</style>
